package com.example.aloy.activity

import android.view.View
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.aloy.databinding.ActivityBottomNavBinding
import com.example.aloy.fragment.BasicFragment


abstract class BottomNavActivity : BasicActivity() {

    private lateinit var fragmentList: ArrayList<BasicFragment>

    // 用来判断父ViewPager中的fragment需不需要拦截点击事件；若需要父ViewPager则不处理点击事件
    private val eventInterceptionList = arrayListOf<Boolean>()

    private val binding: ActivityBottomNavBinding by lazy {
        ActivityBottomNavBinding.inflate(
            layoutInflater
        )
    }

    abstract fun getFragmentList(): ArrayList<BasicFragment>

    abstract fun getBottomNavMenu(): Int

    abstract fun onNavigationItemSelected(itemID: Int)

    override fun getContentView(): View {
        return binding.root
    }

    override fun initView() {
        fragmentList = getFragmentList()
        eventInterceptionList.run {
            for (basicFragment: BasicFragment in fragmentList) {
                add(basicFragment.isInterceptEvent())
            }
        }

        //父ViewPager页面切换监听
        binding.mainViewPager.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                //滑动fragment对应底部按菜单钮选中
                binding.bottomNavView.menu.getItem(position).isChecked = true
                //如果当前Fragment选择拦截事件，则不处理
                binding.mainViewPager.isUserInputEnabled =
                    !eventInterceptionList[binding.mainViewPager.currentItem]
            }
        })
        // 缓存页面的数量
        binding.mainViewPager.offscreenPageLimit = 2
        binding.mainViewPager.adapter = object : FragmentStateAdapter(this) {
            override fun createFragment(position: Int) = fragmentList[position]
            override fun getItemCount() = fragmentList.size
        }
        binding.mainViewPager.setCurrentItem(0, true)

        val menuID = getBottomNavMenu()
        binding.bottomNavView.inflateMenu(menuID)
        binding.bottomNavView.setOnNavigationItemSelectedListener {
            onNavigationItemSelected(it.itemId)
            //表示事件已经被处理了，不需要往上传
            true
        }
    }

    fun switchFragment(index: Int) {
        binding.mainViewPager.setCurrentItem(index, true)
    }


    fun getMainViewPager(): ViewPager2 {
        return binding.mainViewPager
    }


}
